﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CUILoader;
using System.IO;
using System.Reflection;
using System.Xml;
using Converter;
using FUI;
using System.Text.RegularExpressions;

namespace MainProgram
{
    public partial class MobileUIGenerator : Form
    {
        CUIManager m_CUIManager;
        FUIManager m_FUIManager;
        ICUI curItem;
        ICUI curControl;

        public MobileUIGenerator()
        {
            m_CUIManager = new CUIManager();
            if (Directory.GetFiles(Path.Combine(Application.StartupPath, "Plugins"), "*.dll").Length > 0)
                foreach (string Filename in Directory.GetFiles(Path.Combine(Application.StartupPath, "Plugins"), "*.dll"))
                {
                    Assembly Asm = Assembly.LoadFile(Filename);
                    foreach (Type AsmType in Asm.GetTypes())
                    {
                        if (AsmType.GetInterface("ICUI") != null && AsmType.Name != "CUIBase")
                        {
                            ICUI Plugin = (ICUI)Activator.CreateInstance(AsmType);
                            m_CUIManager.LstCUI.Add(Plugin);
                        }
                    }
                }
            InitializeComponent();
            loadToolBox();
        }

        Janus.Windows.ButtonBar.ButtonBarGroup buttonBar1_Group_0;
        public void loadToolBox()
        {
            //Load group
            buttonBar1_Group_0 = new Janus.Windows.ButtonBar.ButtonBarGroup();
            buttonBar1_Group_0.Key = "Group1";
            this.buttonBar1.Groups.AddRange(new Janus.Windows.ButtonBar.ButtonBarGroup[] {
            buttonBar1_Group_0});

            //Load toolbox
            foreach (ICUI item in m_CUIManager.LstCUI)
            {
                Janus.Windows.ButtonBar.ButtonBarItem buttonBar = new Janus.Windows.ButtonBar.ButtonBarItem();
                buttonBar.Icon = ((System.Drawing.Icon)System.Drawing.Icon.ExtractAssociatedIcon(Application.StartupPath + @"\Plugins\Resources\" + item.getName() + ".ico"));
                buttonBar.Key = "Item1";
                buttonBar.Text = item.getName();
                buttonBar.Tag = item;
                buttonBar1_Group_0.Items.AddRange(new Janus.Windows.ButtonBar.ButtonBarItem[] {
                buttonBar});
            }
        }

        private System.Windows.Forms.DataGridView dataGridView1;

        void initPropertiesPanel()
        {
            this.uiPanel1Container.Controls.Clear();
        }

        public void loadProperties()
        {
            initPropertiesPanel();
            this.dataGridView1 = new System.Windows.Forms.DataGridView();

            // 
            // dataGridView1
            // 
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Location = new System.Drawing.Point(22, 42);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.Size = new System.Drawing.Size(240, 150);
            this.dataGridView1.TabIndex = 0;
            this.dataGridView1.Dock = DockStyle.Fill;



            this.uiPanel1Container.Controls.Add(this.dataGridView1);

            DataGridViewTextBoxColumn Column1;
            DataGridViewTextBoxColumn Column2;
            Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            Column1.HeaderText = "Name";
            Column1.Name = "Name";
            Column1.ReadOnly = true;
            Column2.HeaderText = "Value";
            Column2.Name = "Value";
            dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            Column1,
            Column2});

           // curItem.toXML();

            foreach (CAttribute item in curControl.getAttributes())
            {
                //dataGridView1.Rows.Add(
                int index = dataGridView1.Rows.Add();
                DataGridViewRow row = dataGridView1.Rows[index];
                row.Cells["Name"].Value = item.StrName;
                row.Cells["Value"].Value = item.StrValue;
                row.Tag = item;
            }

            curDgv = dataGridView1;
            this.curDgv.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView_CellValueChanged);
        }

        private void buttonBar1_ItemClick(object sender, Janus.Windows.ButtonBar.ItemEventArgs e)
        {
            curItem = (ICUI)((Janus.Windows.ButtonBar.ButtonBarItem)e.Item).Tag;

            string Filename = Path.Combine(Application.StartupPath, "Plugins") + @"\" + curItem.getName() + ".dll";
            Assembly Asm = Assembly.LoadFile(Filename);
            foreach (Type AsmType in Asm.GetTypes())
            {
                if (AsmType.GetInterface("ICUI") != null && AsmType.Name != "CUIBase")
                {
                    ICUI Plugin = (ICUI)Activator.CreateInstance(AsmType);
                    //m_CUIManager.LstCUI.Add(Plugin);
                    curControl = Plugin;
                }
            }

            //loadProperties();

            CUIControl newCUIControl;
            newCUIControl = curControl.getCUIControl();
            newCUIControl.MouseDown += new System.Windows.Forms.MouseEventHandler(this.CUIControl_MouseDown);
            newCUIControl.EClickedPosition = CUIControl.ePosition.Inside;
            //this.newCUIControl.Location = new System.Drawing.Point(85, 38);
            newCUIControl.Name = "newCUIControl";
            newCUIControl.Size = new System.Drawing.Size(100, 50);
            newCUIControl.TabIndex = 0;
            newCUIControl.initCtrl();
            this.uiPanel2Container.Controls.Add(newCUIControl);
        }

        CAttribute getAttributeFromName(List<CAttribute> lstAtt, string strName)
        {
            foreach (CAttribute item in lstAtt)
            {
                if (item.StrName == strName)
                    return item;
            }
            return null;
        }

        private void CUIControl_MouseDown(object sender, MouseEventArgs e)
        {
            CUIControl curTempControl = (CUIControl)sender;
            curControl = curTempControl.ParentCUI;
            //getAttributeFromName(curControl.getAttributes(), "Text").StrValue = "123";
            loadProperties();
        }

        DataGridView curDgv;

        private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            CAttribute att = (CAttribute)this.curDgv.Rows[e.RowIndex].Tag;
            att.StrValue = (string)(this.curDgv.Rows[e.RowIndex].Cells[1].Value);
        }

        //Lưu toàn bộ editor
        private void buttonCommand1_Click(object sender, Janus.Windows.Ribbon.CommandEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "Save UI Editor";
            saveFileDialog.Filter = "XML File|*.xml";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    string StrXMLContent = "";
                    StrXMLContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
                    StrXMLContent += "<Form Name=\"Form1\">";
                    
                    //lần lượt lưu từng Xml của các control ra file
                    foreach (Control myContr in this.uiPanel2Container.Controls)
                    {
                        CUIControl ctr = (CUIControl)myContr;
                        StrXMLContent += ctr.ParentCUI.toXMLString();
                    }
                    StrXMLContent += "</Form>";
                    StreamWriter w = new StreamWriter(saveFileDialog.FileName, false,Encoding.UTF8);
                    w.Write(StrXMLContent);
                    w.Close();
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.Message);
                }
            }
        }

        private void btnNetCFCodeGeneration_Click(object sender, Janus.Windows.Ribbon.CommandEventArgs e)
        {
            //Tim IConverter cho .NETCF
            IConverter NetCFCodeGenerator;
            if (Directory.GetFiles(Path.Combine(Application.StartupPath, @"Plugins\FUIPlugins\dotNETCF"), "*.dll").Length > 0)
                foreach (string Filename in Directory.GetFiles(Path.Combine(Application.StartupPath, @"Plugins\FUIPlugins\dotNETCF"), "*.dll"))
                {
                    Assembly Asm = Assembly.LoadFile(Filename);
                    foreach (Type AsmType in Asm.GetTypes())
                    {
                        if (AsmType.GetInterface("IConverter") != null && AsmType.Name == "CNetCFConverter")
                        {
                            NetCFCodeGenerator = (IConverter)Activator.CreateInstance(AsmType);

                            //Phat sinh FUIs
                            m_FUIManager = new FUIManager();

                            foreach (Control myContr in this.uiPanel2Container.Controls)
                            {
                                CUIControl ctr = (CUIControl)myContr;
                                ICUI cuiControl = ctr.ParentCUI;
                                m_FUIManager.LstFUI.Add(NetCFCodeGenerator.convertFromCUI(cuiControl));
                            }
                            //MessageBox.Show(NetCFCodeGenerate());

                            string strPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
                            strPath = strPath.Substring(0, strPath.LastIndexOf("\\"));
                            FileStream file;
                            file = new FileStream(strPath + "\\CFv35.GeneratedDesigner.cs", FileMode.Create, FileAccess.Write);
                            StreamWriter sw = new StreamWriter(file);
                            sw.Write(NetCFCodeGenerate());
                            sw.Close();
                            file.Close();
                        }
                    }
                }


        }

        //Hàm phát sinh code cho NetCF
        private string NetCFCodeGenerate()
        {
            string strPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            strPath = strPath.Substring(0, strPath.LastIndexOf("\\"));
            FileStream file;
            file = new FileStream(strPath + "\\CFv35.Designer.cs", FileMode.OpenOrCreate, FileAccess.Read);
            StreamReader sr = new StreamReader(file);
            string s = sr.ReadToEnd();
            sr.Close();
            file.Close();

            //Su dung regex de thay cac pattern trong CFv35.Designer.cs
            string pattern = "###Initialization###";
            string replacement = "";
            foreach (IFUI item in m_FUIManager.LstFUI)
            {
                replacement += (item.generateInitialization() + "\n");
            }
            Regex rgx = new Regex(pattern);
            s = rgx.Replace(s, replacement);

            
            pattern = "###Declaration###";
            replacement = "";
            foreach (IFUI item in m_FUIManager.LstFUI)
            {
                replacement += (item.generateDeclaration() + "\n");
            }
            rgx = new Regex(pattern);
            s = rgx.Replace(s, replacement);
            
            return s;
        }


    }
}
